import { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Row, Col, Table, Form, Input, message, Button, Select, Modal, Space } from 'antd';
import { ExclamationCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import CategoryTree from '@/components/CategoryTree';
import request from '@/utils/request';

const apiURL = '/api/services/app/Role/';
const { confirm } = Modal;
const tenantid = localStorage.getItem('tenantId');
const ViewAuth = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [datas, setDatas] = useState<any>({});
  const [Permissions, setPermissions] = useState([]);
  const [superAdmin, setSuperAdmin] = useState(false);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 70,
    },
    {
      title: intl.formatMessage({ id: 'pages.roleName' }),
      dataIndex: 'displayName',
      key: 'displayName',
    },
  ];
  useEffect(() => {
    fetchRoles();
    fetchPermission();
    setSuperAdmin(tenantid === '0' || tenantid === '1' || tenantid != undefined);
  }, [tenantid]);

  const fetchRoles = () => {
    setLoading(true);
    request(apiURL + 'GetAll', {
      method: 'GET',
      params: { SkipCount: 0, MaxResultCount: 100 },
    }).then((response) => {
      setLoading(false);
      setDataSource(response.result.items);
    });
  };

  const fetchPermission = () => {
    request(apiURL + 'GetAllPermissions', {
      method: 'GET',
    }).then((response) => {
      setPermissions(response.result.items);
    });
  };

  const ResetForm = () => {
    var data = {
      id: 0,
    };
    setDatas(data);
    formRef.current.resetFields();
  };

  const onFinish = (values: any) => {
    var act = 'Create';
    if (values.Role.id > 0) {
      act = 'Update';
    }
    values.Role.menuPermission = values.Role.menuPermission.join(',');
    request(apiURL + act, {
      method: act == 'Create' ? 'POST' : 'PUT',
      data: values.Role,
    }).then((response) => {
      message.success(intl.formatMessage({ id: 'pages.save.success' }));
      fetchRoles();
    });
  };

  const handleDel = () => {
    if (datas.name == 'admin') {
      message.error(intl.formatMessage({ id: 'pages.roleAdminCannotDelete' }));
    } else {
      props
        .dispatch({
          type: 'Abp/delete',
          payload: { Id: datas.id },
          control: 'Role',
        })
        .then(() => {
          var resp = props.response;
          if (resp.success) {
            message.success(intl.formatMessage({ id: 'pages.delete.success' }));
            fetchRoles();
            formRef.current.resetFields();
          }
        });
    }
  };

  const showConfirm = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        handleDel();
      },
      onCancel() {},
    });
  };

  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      var datas = selectedRows[0];
      request(apiURL + 'GetRoleForEdit', {
        method: 'GET',
        params: { Id: datas.id },
      }).then((response) => {
        if (response && response.success) {
          datas.permissions = response.result.grantedPermissionNames;
          if (datas && datas.menuPermission && !Array.isArray(datas.menuPermission)) {
            datas.menuPermission = datas.menuPermission.split(',');
          }
          setDatas(datas);
          formRef.current.setFieldsValue({ Role: datas });
        }
      });
    },
    getCheckboxProps: (record: any) => ({
      //disabled: record.name === 'Admin',
      name: record.name,
    }),
  };

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Row gutter={16}>
        <Col span={8}>
          <Card
            title={<FormattedMessage id="pages.roleList" />}
            extra={[
              <Button
                onClick={fetchRoles}
                size="small"
                icon={<SyncOutlined />}
                loading={loading}
              ></Button>,
            ]}
          >
            <Table
              rowKey="id"
              rowSelection={{
                type: 'radio',
                ...rowSelection,
              }}
              dataSource={dataSource}
              columns={columns}
              pagination={false}
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={16}>
          <Card title={<FormattedMessage id="pages.roleConfig" />}>
            <Form {...layout} ref={formRef} onFinish={onFinish}>
              <Form.Item label="id" name={['Role', 'id']} hidden>
                <Input />
              </Form.Item>
              <Form.Item
                name={['Role', 'name']}
                label={<FormattedMessage id="pages.roleName" />}
                rules={[
                  { required: true, message: <FormattedMessage id="pages.roleName.required" /> },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name={['Role', 'displayName']}
                label={<FormattedMessage id="pages.dsiplayName" />}
                rules={[
                  { required: true, message: <FormattedMessage id="pages.dsiplayName.required" /> },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name={['Role', 'description']}
                label={<FormattedMessage id="pages.description" />}
              >
                <Input.TextArea />
              </Form.Item>
              <Form.Item
                label={<FormattedMessage id="pages.grantPermission" />}
                name={['Role', 'permissions']}
              >
                <Select
                  mode="multiple"
                  placeholder={<FormattedMessage id="pages.pleaseSelectPermission" />}
                  allowClear
                >
                  {Permissions.map((item: any, key: any) => {
                    return (
                      <Select.Option key={key} value={item.name}>
                        {item.displayName}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <CategoryTree
                multiple={true}
                layout="Menu"
                width={300}
                name={['Role', 'menuPermission']}
                label={<FormattedMessage id="pages.menuPermission" />}
                disableEdit={!superAdmin}
              />
              <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 4 }}>
                <Space>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    <span>
                      <FormattedMessage id="pages.save" />
                    </span>
                  </Button>
                  <Button onClick={ResetForm}>
                    <FormattedMessage id="pages.reset" />
                  </Button>
                  <Button danger onClick={showConfirm} disabled={datas.id == 0 || !datas.id}>
                    <FormattedMessage id="pages.delete" />
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  currentUser: Abp.currentUser,
  response: Abp.response,
}))(ViewAuth);
